#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include "../common/common.h"

#ifdef DEBUG_IP
    #define SERVERIP "182.92.93.1"
#else
    #define SERVERIP "127.0.0.1"
#endif

#define PORT 4399
#define PORT1 4400

#define INFO1 "info:1"

int main(int argc, const char *argv[])
{
    int sockfd;
    struct sockaddr_in seraddr;
    //char buf_1[1024] = "info:1";
    char buf_recv[1024] = {0};
    int ret;

    memset(buf_recv,0,sizeof(buf_recv));

    socklen_t addrlen = sizeof(seraddr);
    //step 1:打开套接字接口
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (-1 == sockfd)
    {
        perror("socket");
        return -1;
    }
    //step 2: 发送数据
    memset(&seraddr, 0, sizeof(seraddr));
    seraddr.sin_family = AF_INET;
    seraddr.sin_port = htons(PORT);
    seraddr.sin_addr.s_addr = inet_addr(SERVERIP);

#ifdef DEBUG
    while (1)
    {
#endif
        //第一次发送数据，获取本机外网ip和port
        ret = sendto(sockfd, INFO1, sizeof(INFO1), 0, (struct sockaddr *)&seraddr, sizeof(seraddr));
        if (-1 == ret)
        {
            perror("sento");
            return -1;
        }
        //printf("sendto successful!\n");
        //step 3:接受数据
        ret = recvfrom(sockfd, buf_recv, sizeof(buf_recv), 0, (struct sockaddr *)&seraddr, &addrlen);
        if (-1 == ret)
        {
            perror("recvfrom");
            return -1;
        }
        clientInfo *myInfo = (clientInfo *)buf_recv;     
        printf("recv from %s:%d, myIp: %s, myPort:%d\n", inet_ntoa(seraddr.sin_addr), ntohs(seraddr.sin_port), myInfo->ip,myInfo->port); 
#ifdef DEBUG
    }
#endif
    close(sockfd);
    return 0;
}
